import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../common/routers/index.dart';
import '../../../common/utils/loading.dart';
import '../../../common/utils/log_util.dart';
import '../../../common/utils/o2_utils.dart';
import '../../../common/widgets/circle_mask_painter.dart';
import 'index.dart';

enum FaceCheckPageMode {
  /// 人脸识别
  faceDetection,

  /// 人脸注册
  faceRegistration,
}

class FaceCheckPagePage extends GetView<FaceCheckPageController> {
  const FaceCheckPagePage({Key? key}) : super(key: key);

  /// 人脸注册
  static Future<dynamic> startRegistration() async {
    if (!await O2Utils.cameraPermission()) {
      Loading.toast('scan_no_camera_permission'.tr);
      return null;
    }

    return await Get.toNamed(O2OARoutes.commonFaceCheckPagePage,
        arguments: {'mode': FaceCheckPageMode.faceRegistration});
  }

  /// 人脸比对
  static Future<dynamic> startDetection() async {
    if (!await O2Utils.cameraPermission()) {
      Loading.toast('scan_no_camera_permission'.tr);
      return null;
    }
    return await Get.toNamed(O2OARoutes.commonFaceCheckPagePage,
        arguments: {'mode': FaceCheckPageMode.faceDetection});
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return Stack(
      children: [
        _faceRecognitionArea(),
        _faceRecognitionAreaCalc(),
        _animationWidget(context),
        // 人脸识别区域遮盖层 白色的背景
        Positioned.fill(
          child: CustomPaint(
            painter: FaceRecognitionOverlay(120),
          ),
        ),
        _titleWidget(context),
        _messageWidget(context),
        _faceRegistrationBtn(),
        closeBtn() //黑色的按钮
      ],
    );
  }

  /// 人脸识别区域  相机预览
  Widget _faceRecognitionArea() {
    return Center(
        child: Obx(() => Transform.scale(
            scale: controller.state.scale, // 缩小为 50%
            child: Transform.flip(
                flipX: true,
                child: CameraPreview(controller.getCameraController(),
                    key: controller.cameraPreviewKey)))));
  }

  /// 人脸识别区域大小计算
  Widget _faceRecognitionAreaCalc() {
    return Builder(
      builder: (context) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          final renderBox = controller.cameraPreviewKey.currentContext
              ?.findRenderObject() as RenderBox?;
          if (renderBox != null) {
            final size = renderBox.size;
            controller.changeScale(size);
          }
        });
        return const SizedBox(); // 不渲染任何UI
      },
    );
  }

  /// 扫描动画
  Widget _animationWidget(BuildContext context) {
    return AnimatedBuilder(
      animation: controller.animation,
      builder: (context, child) {
        final screenHeight = MediaQuery.of(context).size.height;
        final top = (controller.animation.value) * screenHeight;
        return Positioned(
            left: 20,
            top: top,
            width: MediaQuery.of(context).size.width - 40,
            height: 2,
            child: Container(
                decoration: const BoxDecoration(color: Colors.green)));
      },
    );
  }
  /// 标题
  Widget _titleWidget(BuildContext context) {
    return Align(
        alignment: Alignment.topCenter,
        child: Padding(
            padding: const EdgeInsets.only(top: 36, left: 16, right: 16),
            child: Obx(() =>
                controller.state.mode.value == FaceCheckPageMode.faceDetection
                    ? Text('common_ali_face_title_detection'.tr,
                        style: Theme.of(context).textTheme.titleMedium)
                    : Text('common_ali_face_title_registration'.tr,
                        style: Theme.of(context).textTheme.titleMedium))));
  }

  /// 提示信息
  Widget _messageWidget(BuildContext context) {
    return Align(
        alignment: Alignment.topCenter,
        child: Padding(
            padding: const EdgeInsets.only(top: 81, left: 16, right: 16),
            child: Obx(() =>
                controller.state.mode.value == FaceCheckPageMode.faceDetection
                    ? Text('common_ali_face_detection_tip'.tr,
                        style: Theme.of(context).textTheme.bodySmall)
                    : Text('common_ali_face_registration_tip'.tr,
                        style: Theme.of(context).textTheme.bodySmall))));
  }

  /// 人脸拍摄按钮
  Widget _faceRegistrationBtn() {
    return Align(
        alignment: Alignment.bottomCenter,
        child: Obx(
            () => controller.state.mode.value == FaceCheckPageMode.faceDetection
                ? const SizedBox()
                : Padding(
                    padding: const EdgeInsets.only(bottom: 48),
                    child: ElevatedButton(
                        onPressed: () async {
                          await controller.captureAndUploadPhoto();
                        },
                        child: Text('common_ali_face_registration_btn'.tr)))));
  }

  /// 关闭按钮
  Widget closeBtn() {
    return Align(
        alignment: Alignment.topLeft,
        child: Padding(
            padding: const EdgeInsets.only(left: 16, top: 24),
            child: IconButton(
                onPressed: () {
                  Get.back();
                },
                icon: const Icon(Icons.close),
                color: Colors.black,
                iconSize: 36)));
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<FaceCheckPageController>(
      builder: (_) {
        return Scaffold(
          body: SafeArea(
            child: Obx(() => controller.state.isCameraInitialized
                ? _buildView(context)
                : const Center(child: CircularProgressIndicator())),
          ),
        );
      },
    );
  }
}
